//
//  MyTextView.m
//  FlyBusBusiness
//
//  Created by Felix on 2017/12/28.
//  Copyright © 2017年 raxtone. All rights reserved.
//

#import "MyTextView.h"

@implementation MyTextView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        // 通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}

/**
 *  监听文字改变
 */
-(void)textDidChange {
    // 重绘 (重新调用) setNeedsDisplay会调用自动调用drawRect方法
    [self setNeedsDisplay];
}

-(void)setPlaceholder:(NSString *)placeholder {
    _placeholder = [placeholder copy];
    [self setNeedsDisplay];
}

-(void)setPlaceholderColor:(UIColor *)placeholderColor {
    _placeholderColor = [placeholderColor copy];
    [self setNeedsDisplay];
}

-(void)setText:(NSString *)text {
    [super setText:text];
    [self setNeedsDisplay];
}
-(void)setAttributedText:(NSAttributedString *)attributedText {
    [super setAttributedText:attributedText];
    [self setNeedsDisplay];
}

-(void)setFont:(UIFont *)font {
    [super setFont:font];
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    // 如果有输入文字,就直接返回,不画占位文字
    if(self.hasText)
        return;
    // 文字属性
    NSMutableDictionary *attributesText = [NSMutableDictionary dictionary];
    attributesText[NSFontAttributeName] = [UIFont systemFontOfSize:12];
    attributesText[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor:[UIColor lightGrayColor];
    CGFloat x = 8;
    CGFloat w = rect.size.width - 2 * x;
    CGFloat y = 8;
    CGFloat h = rect.size.height - 2 * y;
    CGRect placeholderRect = CGRectMake(x, y, w, h);
    [self.placeholder drawInRect:placeholderRect withAttributes:attributesText];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
